package com.xxg.curd.impl;

import com.xxg.curd.ex.CurdSQLException;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;

/**
 * 数据集处理器
 */
public class DefaultResultFunction implements Function<ResultSet,List<Map<String,Object>>> {

    @Override
    public List<Map<String, Object>> apply(ResultSet res) {
        List<Map<String, Object>> list = new ArrayList<>();

        try {
            ResultSetMetaData mata = res.getMetaData();
            int columnCount = mata.getColumnCount() + 1;
            while (res.next()) {
                Map<String,Object> row = new LinkedHashMap<>();

                for (int i = 1; i < columnCount; i++) {
                    String name = mata.getColumnName(i);
                    row.put(name,res.getObject(i));
                }

                list.add(row);
            }
        } catch (SQLException e) {
            throw new CurdSQLException(e);
        }

        return list;
    }
}
